﻿/* Autor: Achim Schnell */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AppFx.ComponentModel.Descriptive;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests.ComponentModel.Descriptive
{
	[TestClass]
	public class Test_CompiledPropertyDescriptor
	{
		[TestMethod]
		[Description("Testet, ob der CompiledPropertyDescriptor erstellt werden kann.")]
		public void Can_CreateCompiledPropertyDescriptor()
		{
			Type t = typeof(CustomType);
			CustomType o = new CustomType();

			PropertyInfo[] pis = t.GetProperties();
			foreach (PropertyInfo pi in pis)
				new CompiledPropertyDescriptor(t, pi);
		}

		[TestMethod]
		[Description("Testet, ob der CompiledPropertyDescriptor Werte aus public-Klassen auslesen kann.")]
		public void Can_GetValues()
		{
			Type t = typeof(CustomType);
			CustomType o = new CustomType() { Title = "Herr", Name = "Max", LastName = "Mustermann" };

			PropertyInfo[] pis = t.GetProperties();
			IList<CompiledPropertyDescriptor> descriptors = new List<CompiledPropertyDescriptor>();
			foreach (PropertyInfo pi in pis)
			{
				CompiledPropertyDescriptor descriptor = new CompiledPropertyDescriptor(t, pi);
				descriptors.Add(new CompiledPropertyDescriptor(t, pi));
			}

			Assert.IsTrue(o.Title == descriptors.Where(d => d.Name == "Title").Single().GetValue(o).ToString());
			Assert.IsTrue(o.Name == descriptors.Where(d => d.Name == "Name").Single().GetValue(o).ToString());
			Assert.IsTrue(o.LastName == descriptors.Where(d => d.Name == "LastName").Single().GetValue(o).ToString());
		}

		[TestMethod]
		[Description("Testet, ob der CompiledPropertyDescriptor Werte aus public-Klassen setzen kann.")]
		public void Can_SetValues()
		{
			Type t = typeof(CustomType);
			CustomType o = new CustomType() { Title = "Herr", Name = "Max", LastName = "Mustermann" };

			PropertyInfo[] pis = t.GetProperties();
			IList<CompiledPropertyDescriptor> descriptors = new List<CompiledPropertyDescriptor>();
			foreach (PropertyInfo pi in pis)
			{
				CompiledPropertyDescriptor descriptor = new CompiledPropertyDescriptor(t, pi);
				descriptors.Add(new CompiledPropertyDescriptor(t, pi));
			}

			descriptors.Where(d => d.Name == "Title").Single().SetValue(o, "Frau");
			descriptors.Where(d => d.Name == "Name").Single().SetValue(o, "Marina");
			descriptors.Where(d => d.Name == "LastName").Single().SetValue(o, "Mustermann");

			Assert.IsTrue("Frau" == descriptors.Where(d => d.Name == "Title").Single().GetValue(o).ToString());
			Assert.IsTrue("Marina" == descriptors.Where(d => d.Name == "Name").Single().GetValue(o).ToString());
			Assert.IsTrue("Mustermann" == descriptors.Where(d => d.Name == "LastName").Single().GetValue(o).ToString());
		}
	}

	public class CustomType
	{
		public string Title { get; set; }

		public string Name { get; set; }

		public string LastName { get; set; }
	}
}
